/**
 * Created by duqunxing on 2018/1/15.
 */
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {API, PermissionType} from '../constants/constants';
import {RequestUtil} from "../util/request-util";
import {LogUtil} from "../util/log-util";
import {Menu} from '../models/menu';
import {Observer} from 'rxjs/Observer';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class MenusService {

  constructor(
    private requestUtil: RequestUtil,
    private logUtil:LogUtil
  ) { }
  //authorization/types/{menus|operations|resources}
  getPermissions(type:string):Observable<any>{
    if(!!!type){
      this.logUtil.warn("request cancel");
      return;
    }
    let uri = API.getPermissions+type+".json";
    return this.requestUtil.get(uri);
  }

  getFisrtLevelMenus():Observable<any>{
    let uri = API.getFirstLevelMenus;
    return this.requestUtil.get(uri);
  }
  getChildMenus(id:string):Observable<any>{
    let uri = API.getChildMenus.replace("{id}",id);
    return this.requestUtil.get(uri);
  }

  checkPermission(url: string): Promise<string> {

    return this.getPermissions(PermissionType.menus).toPromise().then(
      result => {
        let permission: Array<Menu> = result.data.filter(function (menu: Menu) {
          if (menu.url == url) {
            return true;
          }
          return false;
        });

        if (permission.length == 1) {
          return permission[0].url + ';mid=' + permission[0].id;
        }
        return null;
      },
      error => {
        this.logUtil.error(error);
        return null;
      }
    );
  }
}
